#include <iostream>
using std::cout;
using std::endl;

// 前向声明AutoRelease
class AutoRelease; 

class Singleton{
    friend class AutoRelease;

public:
    static Singleton* getInstance();

    void print() { cout << "Singleton working" << endl; } // 示例方法

    //    void Destroy(){
    //        if(_pInstance != nullptr){
    //            delete _pInstance;
    //            _pInstance = nullptr;
    //        }
    //    }

private:
    static Singleton *_pInstance; 

    Singleton() = default;  // 只定义不实现会报错
    ~Singleton() = default;

    Singleton(const Singleton&) = delete;
    Singleton operator=(const Singleton&) = delete;
};

// 初始化静态成员
Singleton* Singleton::_pInstance = nullptr;

class AutoRelease{
public:
    AutoRelease(Singleton* ptr)
        :_ptr(ptr){
        cout << "AutoRelease" << endl;
    }

    ~AutoRelease(){
        if(_ptr != nullptr){
            delete _ptr;    // 此处间接访问了singleton的私有成员，需要添加友元
            _ptr = nullptr;

            cout << "~AutoRelease" << endl;
        }
    }

    // 智能指针属于包装器重载，其它运算符应由Singleton自己重载
    Singleton* operator->(){
        return _ptr;
    }

    Singleton& operator*(){
        return *_ptr;
    }

private:
    Singleton* _ptr;
};

Singleton* Singleton::getInstance(){
    if(_pInstance == nullptr){
        _pInstance = new Singleton();
        static AutoRelease ar(_pInstance);  // 托管指针
        cout << "getInstance" << endl;
    }
    return _pInstance;
}

void test(){
//  AutoRelease();    // 错误调用，创建对象后立即销毁

//  正常销毁
//  Singleton::getInstance()->print();
//  Singleton::getInstance()->print();

//  double_free
    AutoRelease ar(Singleton::getInstance());
    AutoRelease ar2(Singleton::getInstance());
}

int main()
{
    test();
    return 0;
}

